package com.dfiov.cloud.msmtools.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.dfiov.cloud.msmtools.mapper.msaccount",
        sqlSessionTemplateRef = "msaccountSqlSessionTemplate",
        sqlSessionFactoryRef = "msaccountSqlSessionFactory")
public class MsAccountDataSourceConfig {
    @Bean(name = "msaccountDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.msaccount")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "msaccountSqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("msaccountDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/msaccount/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean(name = "msaccountSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("msaccountSqlSessionFactory") SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryBean.getObject());
    }

    @Bean("msaccountDataSourceTransactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("msaccountDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
